package juc.test;

import org.elasticsearch.index.fielddata.RamAccountingTermsEnum;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Depot {
    private int size;
    private int capacity;
    private Lock lock;
    private Condition fullCondition;
    private Condition emptyCondition;

    public Depot(int capacity){
        this.capacity = capacity;
        lock = new ReentrantLock();
        emptyCondition = lock.newCondition();
        fullCondition = lock.newCondition();
    }

    public void produce(int no){
        lock.lock();
        int left = no;
        try{
            while(left > 0){
                while(size >= capacity){
                    System.out.println(Thread.currentThread() + "before await()");
                    fullCondition.await();
                    System.out.println(Thread.currentThread() + "after await()");
                    int inc = (left + size) > capacity ? (capacity - size) : left;
                    left -= inc;
                    size += inc;
                    System.out.println("produce = " + inc + ",size = " + size);
                    emptyCondition.signal();
                }
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }finally {
            lock.unlock();
        }
    }

    public void consumer(int no){
        lock.lock();
        int left = no;
        try{
            System.out.println(Thread.currentThread() + "before await()");
            emptyCondition.await();
            System.out.println(Thread.currentThread() + "after await()");
            int inc = (left + size) > capacity ? (capacity - size) : left;
            left -= inc;
            size -= inc;
            System.out.println("produce = " + inc + ",size = " + size);
            emptyCondition.signal();
        }catch (Exception e){
            System.out.println(e.getMessage());
        }finally {
            lock.unlock();
        }
    }
}
